Shiny.addCustomMessageHandler("parset_values", function (message) {

    data = message[0];
    data1 = transposeData(message[1]);

    var scopes = ["pais", "regiao", "uf", "mesorregiao", "microrregiao", "municipio"];

    var margin = {top: 0, right: 50, bottom: 50, left: 0},
	width = window.innerWidth - margin.left - margin.right,
	height = window.innerHeight - margin.top - margin.bottom;

    var chart = d3.parsets()
	.width(width)
	.height(height)
	.dimensions(Object.keys(message[1]));

    var parset = d3.select("#parset_area").append("svg")
	.attr("width", width + margin.left + margin.right)
	.attr("height", height + margin.top + margin.bottom);

    parset.datum(data1).call(chart);

    function transposeData(d) {

	var values = Object.keys(d);

        var len = d.cnae_secao.length;
        var datainsert = new Object();
        var dataTransposed = [];

        for (var i = 0; i < len; i++) {

	    values.forEach(function (v) {
                datainsert[v] = d[v][i];
            });

	    dataTransposed.push(datainsert);
	    datainsert = new Object();
	}

	return dataTransposed;
    }

    //Treemap code
   var tmargin = {
        top: 25,
        right: 0,
        bottom: 0,
        left: 0
    },
       twidth = window.innerWidth * 0.95,
       theight = window.innerHeight * 0.6,
       formatNumber = d3.format(",d"),
       transitioning,
       hovering;

    var tm_tooltip = d3.select("body")
        .append("div")
        .style("position", "absolute")
        .style("z-index", "10")
        .style("visibility", "hidden")
        .style("color", "white")
        .style("padding", "8px")
        .style("background-color", "rgba(0, 0, 0, 0.75)")
        .style("border-radius", "6px")
        .style("font", "12px sans-serif")
        .text("tooltip");

    var x = d3.scaleLinear()
        .domain([0, twidth])
        .range([0, twidth]);

    var y = d3.scaleLinear()
        .domain([0, theight - tmargin.top - tmargin.bottom])
        .range([0, theight - 3 * tmargin.top - tmargin.bottom]);

    var c = [];

    function q(d) {
        for (var i = 0; i < d.children.length; i++) {
            c[i] = d.children[i].value;
        }

        return c.sort(function (a, b) {
            return (a - b);
        });
    }
    q(data);

    var maxValue = c[c.length - 1];
    var minValue = maxValue / 9;

    var color = d3.scaleThreshold()
        .domain([minValue, minValue * 2, minValue * 3, minValue * 4, minValue * 5, minValue * 6, minValue * 7, minValue * 8])
        .range(d3.schemeBlues[9]);

    var format = d3.format(",d");
    var createTreemap;
    var treemap, grandparent;

    updateDrillDown();

    function updateDrillDown() {
        if (treemap) {
            treemap.selectAll("*").remove();
        } else {
            treemap = d3.select("#treemap_area").append("svg")
                .attr("width", twidth + tmargin.left + tmargin.right)
                .attr("height", theight + tmargin.bottom + tmargin.top)
            //.style("tmargin-left", -tmargin.left + "px")
            //.style("tmargin.right", -tmargin.right + "px")
                .append("g")
                .attr("transform", "translate(" + tmargin.left + "," + tmargin.top + ")")
                .style("shape-rendering", "crispEdges");

            grandparent = treemap.append("g")
                .attr("class", "grandparent");

            grandparent.append("rect")
                .style("fill", "#ADEAEA")
                .style("padding", "1px")
                .attr("y", -tmargin.top)
                .attr("width", twidth)
                .attr("height", tmargin.top);

            grandparent.append("text")
                .attr("x", 6)
                .attr("y", 6 - tmargin.top)
                .attr("dy", ".75em");

            createTreemap = d3.treemap()
                .tile(d3.treemapBinary)
                .size([twidth, theight - 10])
                .round(false)
                .paddingInner(0);
        }

        var root = d3.hierarchy(data)
            .eachBefore(function (d) {
                d.id = (d.parent ? d.parent.id + "." : "") + d.data.name;
            })
            .sum(function (d) {
                return d.value;
            })
            .sort(function (a, b) {
                return b.height - a.height || b.value - a.value;
            });

        initialize(root);
        accumulate(root);
        layout(root);
        createTreemap(root);
        display(root);
    };

    function initialize(root) {
        root.x = root.y = 0;
        root.x1 = twidth;
        root.y1 = theight;
        root.depth = 0;
    }

    function accumulate(d) {
        return (d._children = d.children) ?
            d.value = d.children.reduce(function (p, v) {
                return p + accumulate(v);
            }, 0) : d.value;
    }

    function layout(d) {
        if (d._children) {
            d._children.forEach(function (c) {
                c.x0 = d.x0 + c.x0 * d.x1;
                c.y0 = d.y0 + c.y0 * d.y1;
                c.x1 *= (d.x1 - d.x0);
                c.y1 *= (d.y1 - d.y0);
                c.parent = d;
                layout(c);
            });
        }
    }

    function display(d) {
        grandparent
            .datum(d.parent)
            .on("click", transition)
            .select("text")
            .text(name(d));


        var g1 = treemap.insert("g", ".grandparent")
            .datum(d)
            .attr("class", "depth");

        var g = g1.selectAll("g")
            .data(d._children)
            .enter().append("g").style("opacity", 1);

        g.filter(function (d) {
            return d._children;
        })
            .classed("children", true)
            .on("click", transition);

        var children = g.selectAll(".child")
            .data(function (d) {
                return d._children || [d];
            })
            .enter().append("g") //SHOW CHILDREN FROM TREEMAP VIEW
            .style("opacity", 0.7); // DEFINES THE OPACITY OF THE INTERNAL NODES

        children.append("rect")
            .attr("class", "child")
            .call(rect)
            .append("title")
            .text(function (d) {
                return d.data.name + " (" + formatNumber(d.data.value) + ")";
            });

        children.append("text")
            .attr("class", "ctext").style("font-size", "14px")
            .text(function (d) {
                return d.data.name;
            })
            .call(text2);

        g.append("rect")
            .attr("class", "parent")
            .call(rect);

        //MOUSEOVER: SHOW CHILDREN OF THE NODES
        g.selectAll("rect").classed("parent", true).on("mouseover", function (d) {
            d3.select(this).style("opacity", 0.3); //.
            tm_tooltip.html(d.data.name + "<br/>" + formatNumber(d.data.value));
            tm_tooltip.transition();
            return tm_tooltip.style("visibility", "visible").style("opacity", 1);
            //children.select("g").style("opacity", 1);
        });
        //MOUSEOUT: HIDE CHILDREN OF THE NODES
        g.selectAll("rect").classed("parent", false).on("mouseout", function () {
            d3.select(this).style("opacity", 1);
            return tm_tooltip.style("visibility", "hidden");
        });

        g.selectAll("rect").classed("parent", false).on("mousemove", function () {
            d3.select(this).style("opacity", 0.3);
            tm_tooltip.style("opacity", 1);
            return tm_tooltip.style("top", (d3.event.pageY - 10) + "px")
		.style("left", (d3.event.pageX + 10) + "px");
        });

        var t = g.append("text")
            .attr("class", "ptext").style("font-weight", "bold")
            .attr("dy", ".75em");

        t.append("tspan")
            .attr("font-weight", "bold")
            .text(function (d) {
                return d.data.name;
            });

        t.append("tspan")
            .attr("dy", "1.0em")
            .text(function (d) {
                return formatNumber(d.data.value);
            });

        t.call(text);

        g.selectAll("rect")
            .style("fill", function (d) {
                return color(d.data.value);
            });

        function transition(d) {
	    //handle parallel sets data
	    Shiny.onInputChange("scope", scopes[d.depth]);
            Shiny.onInputChange("name", d.data.name);
	    Shiny.addCustomMessageHandler("treemap_values_change", function (message) {

		chart = d3.parsets()
		    .width(width)
		    .height(height)
		    .dimensions(Object.keys(message));

		var data = transposeData(message);
		d3.select("#parset_area svg").remove();

		parset = d3.select("#parset_area").append("svg")
		    .attr("width", width + margin.left + margin.right)
		    .attr("height", height + margin.top + margin.bottom);

		parset.datum(data).call(chart);

	    });

            if (transitioning || !d) return;
            if (transitioning || !d) return;
            transitioning = true;
            var g2 = display(d),
                t1 = g1.transition().duration(750),
                t2 = g2.transition().duration(750);
            // Update the domain only after entering new elements.
            x.domain([d.x0, d.x0 + (d.x1 - d.x0)]);
            y.domain([d.y0, d.y0 + (d.y1 - d.y0)]);

            // Enable anti-aliasing during the transition.
            treemap.style("shape-rendering", null);

            // Draw child nodes on top of parent nodes.
            //treemap.selectAll(".depth").sort(function(a, b) {
            //console.log('.depth sort a ' + a.depth + ' b ' + b.depth);
            //return a.depth - b.depth; });

            // Fade-in entering text.
            g2.selectAll("text").style("fill-opacity", 0);

            // Transition to the new view.
            t1.selectAll(".ptext")
		.call(text)
		.style("fill-opacity", 0)
		.style("font-weight", "bold"); //.style("font-size", "12px");
            t2.selectAll(".ptext")
		.call(text)
		.style("fill-opacity", 1)
		.style("font-weight", "bold"); //.style("font-size", "12px");
            t1.selectAll(".ctext")
		.call(text2)
		.style("fill-opacity", 0);
            t2.selectAll(".ctext")
		.call(text2)
		.style("fill-opacity", 1);
            t1.selectAll("rect")
		.call(rect);
            t2.selectAll("rect")
		.call(rect);

            // Remove the old node when the transition is finished.
            t1.remove().on("end", function () {
                treemap.style("shape-rendering", "crispEdges");
                transitioning = false;
            });
        }
        return g;
    }

    function make_title(d) {
        return d ? d.data.name + " (" + formatNumber(d.data.value) + ")" : d.data.name + " (" + formatNumber(d.data.value) + ")";
    }

    function text(text) {
        text.selectAll("tspan")
            .attr("x", function (d) {
                return x(d.x0) + 5;
            });
        text.attr("x", function (d) {
            return x(d.x0) + 5;
        })
            .attr("y", function (d) {
                return y(d.y0) + 3;
            })
            .style("opacity", function (d) {
                var w = x(d.x1) - x(d.x0);
                return this.getComputedTextLength() <= w ? 1 : 0;
            })
            .style("font-size", "10px");
    }

    function text2(text) {
        text
            .attr("x", function (d) {
                return x(d.x1) - this.getComputedTextLength() - 2;
            })
            .attr("y", function (d) {
                return y(d.y1) - 2;
            })
            .style("opacity", function (d) {
                var w = x(d.x1) - x(d.x0);
                return this.getComputedTextLength() <= w ? 1 : 0;
            })
            .style("font-size", "14px");
    }

    function rect(rect) {
        rect.attr("x", function (d) {
            return x(d.x0);
        })
            .attr("y", function (d) {
                return y(d.y0);
            })
            .attr("width", function (d) {
                var w = x(d.x1) - x(d.x0) - 1;
                return w;
            })
            .attr("height", function (d) {
                var h = y(d.y1) - y(d.y0);
                return h;
            })
            .style("stroke", "darkblue")
            .style("stroke-width", 1);
    }

    function name(d) {
        return d.parent ? name(d.parent) + " -> " + d.data.name + " (" + formatNumber(d.data.value) + ")" : d.data.name + " (" + formatNumber(d.data.value) + ")";
    }

});
